﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Diagnostics;

namespace ERPStudio
{
    public partial class FrmTreeRezumat : FrmRezumat
    {
        private Boolean _ReloadTree = false;
        public Boolean ReloadTree 
        {
            get { return _ReloadTree; }
            set { _ReloadTree = value; }
        }

        public Boolean newTreeDataControl = false;
        public class NodeInfo
        {
            public Object ID = null;
            public Int32 IDJurnal = 0;
            public Object GridRowNo = null;
            public NodeInfo(Object id)
            {
                ID = id;
            }
            public NodeInfo(Object id,Int32 jurnal)
            {
                ID = id;
                IDJurnal = jurnal;
            }
            public NodeInfo(Object id, Int32 jurnal,Object rNr)
            {
                ID = id;
                IDJurnal = jurnal;
                GridRowNo = rNr;
            }


        }
        
        public event TreeLoadHandler HandleFillTree;
        /// <summary>
        /// contrul de tip tree
        /// </summary>
        private TreeView _localTree = null;
        public TreeView localTree
        {
            get { return _localTree;}
            set { _localTree = value;}
        }
        /// <summary>
        /// coloana parinte
        /// </summary>
        private String _coloanaParinte = null;
        public string ColoanaParinte
        {
            get { return _coloanaParinte; }
            set { _coloanaParinte = value; }
        }
        /// <summary>
        /// coloana index
        /// </summary>
        private String _coloanaPK = null;
        public string ColoanaPK
        {
            get { return _coloanaPK; }
            set { _coloanaPK = value; }
        }

        private String _coloanaNume = null;
        public string ColoanaNume
        {
            get { return _coloanaNume; }
            set { _coloanaNume = value; }
        }

        private String _coloanaJurnal = null;
        public string ColoanaJurnal
        {
            get { return _coloanaJurnal; }
            set { _coloanaJurnal = value; }
        }
        /// <summary>
        /// se adauga un fitru suplimentar in functie de situatie
        /// </summary>
        private String _filtru = String.Empty;
        public string Filtru
        {
            get { return _filtru; }
            set { _filtru = value; }
        }

        public string txtRoot = "Root";
        public FrmTreeRezumat(ModuleClass mInfo)
            : base(mInfo)
        {
            InitializeComponent();

        }
        /// <summary>
        /// search for tree control and return true if find it
        /// </summary>
        private Boolean SearchForTreeControl(Control parent)
        {
            foreach (Control ctl in parent.Controls)
            {
                if (ctl.Controls != null)
                    if (SearchForTreeControl(ctl))
                        return true;
                if (ctl is TreeView || ctl is RelationTextBox.dscTreeView)
                {
                    localTree = ctl as TreeView;
                    return true;
                }
            }
            return false;

        }


        /// <summary>
        /// CONSTRUCTORUL FACUT SPECIAL CA SA MEARGA DESIGNERUL
        /// </summary>
        public FrmTreeRezumat()
        {
            InitializeComponent();
            numeMacheta = Text;
        }


        public void LoadTree(TreeNode tr, SqlConnection sqlConn, String CodUnitate)
        {
            if (ColoanaParinte == null)
            {
                MessageBox.Show("Setati Coloana Parinte inainte de a deschide macheta !");
                return;
            }
            //sterge subnodurile
            //tr.Nodes.Clear();
            //campparinte = IdDepartParinte
            NodeInfo tag = (NodeInfo)tr.Tag;
            if (listBndSourceMain.Count == 0)
                return;

            listBndSourceMain[0].Filter = ColoanaParinte + "=" + (tag.ID.GetType() == typeof(String) ? "'" : String.Empty) +
                tag.ID.ToString() + (tag.ID.GetType() == typeof(String) ? "'" : String.Empty) +
                " AND CodUnitate =" + ModuleInfo.CodUnitate.ToString() + (_coloanaPK != null ? (" AND " + _coloanaParinte + "<>" + _coloanaPK) : String.Empty) + _filtru;
            

            Boolean areFii = false;
            Trace.Assert(_coloanaNume!=null,"Nu a fost setata coloana cu numele!");
            Trace.Assert(_coloanaPK != null, "Nu a fost setata coloana index!");
            int rowNr = 0;

            if (tr.Nodes.Count == 0)
            {
                foreach (DataRowView dr in listBndSourceMain[0])
                {
                    TreeNode tnAdd = null;
                    if (dr[_coloanaNume].ToString() != "N/A")
                    {
                        String nume = String.Empty;
                        if (dr[_coloanaNume].GetType() == typeof(DateTime))
                            nume = ((DateTime)dr[_coloanaNume]).ToShortDateString();
                        else
                            nume = dr[_coloanaNume].ToString().Trim();
                        tnAdd = tr.Nodes.Add(nume);
                        tnAdd.ImageIndex = 1;
                        if (dr[_coloanaPK].GetType() == typeof(String))
                        {
                            if (_coloanaJurnal != null)
                                tnAdd.Tag = new NodeInfo(dr[_coloanaPK], Convert.ToInt32(dr[_coloanaJurnal]));
                            else
                                tnAdd.Tag = new NodeInfo(dr[_coloanaPK]);
                        }
                        else
                        {
                            if (_coloanaJurnal != null)
                                tnAdd.Tag = new NodeInfo(Convert.ToInt32(dr[_coloanaPK]), Convert.ToInt32(dr[_coloanaJurnal]));
                            else
                                tnAdd.Tag = new NodeInfo(Convert.ToInt32(dr[_coloanaPK]));
                        }
                        //((NodeInfo)tnAdd.Tag).RowNo = rowNr;
                        rowNr++;
                        areFii = true;
                    }

                }
            }
            else
            {
                foreach (TreeNode tnchild in tr.Nodes)
                {
                    NodeInfo ni = tnchild.Tag as NodeInfo;
                    int poz = listBndSourceMain[0].Find(_coloanaPK, ni.ID);
                    if (poz == -1)
                        tr.Nodes.Remove(tnchild);
                    else
                    {
                        DataRowView dr = listBndSourceMain[0][poz] as DataRowView;
                        if (dr != null)
                        {
                            String nume = String.Empty;
                            if (dr[_coloanaNume].GetType() == typeof(DateTime))
                                nume = ((DateTime)dr[_coloanaNume]).ToShortDateString();
                            else
                                nume = dr[_coloanaNume].ToString().Trim();
                            if (nume != tnchild.Text)
                                tnchild.Text = nume;

                        }
                    }

                }

            }

            if (areFii)
                tr.ImageIndex = 0;
            foreach (TreeNode tr1 in tr.Nodes)
                LoadTree(tr1, sqlConn,CodUnitate);
            tr.ExpandAll();
            listBndSourceMain[0].Filter = ColoanaParinte + "=" + (tag.ID.GetType() == typeof(String) ? "'" : String.Empty) +
                tag.ID.ToString() + (tag.ID.GetType() == typeof(String) ? "'" : String.Empty) +
                " AND CodUnitate =" + ModuleInfo.CodUnitate.ToString() + (_coloanaPK != null ? (" AND " + _coloanaParinte + "<>" + _coloanaPK) : String.Empty) + _filtru;

        }

        public void LoadTreeAndGrid(TreeNode tr, SqlConnection sqlConn, String CodUnitate,DataGridView dgv)
        {
            if (dgv.Columns.Count == 0)
                return;
            if(tr.Parent==null)
            {
                //daca se adauga la nodul parinte 
                int  rd = dgv.Rows.Add();
                ((NodeInfo)tr.Tag).GridRowNo = dgv.Rows[rd]; //DataGridViewRow
                dgv.Rows[rd].Tag = tr;
                dgv.Rows[rd].ReadOnly = true;
            }

            //sterge subnodurile
            tr.Nodes.Clear();
            //campparinte = IdDepartParinte
            NodeInfo tag = (NodeInfo)tr.Tag;
            String _localTableName = listBndSourceMain[0].DataMember;
            SqlCommand cmd = new SqlCommand("SELECT * FROM " + _localTableName + " WHERE  " + ColoanaParinte + "=" + (tag.ID.GetType() == typeof(String) ? "'" : String.Empty) +
                tag.ID.ToString() + (tag.ID.GetType() == typeof(String) ? "'" : String.Empty) +
                (CodUnitate != String.Empty ? (" AND CodUnitate =" + CodUnitate) : String.Empty) + " AND " + _coloanaParinte + "<>" + _coloanaPK + _filtru,
                sqlConn);
            if (sqlConn.State != ConnectionState.Open)
                sqlConn.Open();
            SqlDataReader dataReader = cmd.ExecuteReader();


            Boolean areFii = false;
            Trace.Assert(_coloanaNume != null, "Nu a fost setata coloana cu numele!");
            Trace.Assert(_coloanaPK != null, "Nu a fost setata coloana index!");
            int rowNr = 0;
            while (dataReader.Read())
            {
                TreeNode tnAdd = null;
                if (dataReader[_coloanaNume].ToString() != "N/A")
                {
                    String nume = String.Empty;
                    if (dataReader[_coloanaNume].GetType() == typeof(DateTime))
                        nume = ((DateTime)dataReader[_coloanaNume]).ToShortDateString();
                    else
                        nume = dataReader[_coloanaNume].ToString();
                    tnAdd = tr.Nodes.Add(nume.Trim() + "(" + dataReader[_coloanaPK].ToString().Trim() + ")");
                    tnAdd.ImageIndex = 1;
                    if (dataReader[_coloanaPK].GetType() == typeof(String))
                    {
                        if (_coloanaJurnal != null)
                            tnAdd.Tag = new NodeInfo(dataReader[_coloanaPK], Convert.ToInt32(dataReader[_coloanaJurnal]));
                        else
                            tnAdd.Tag = new NodeInfo(dataReader[_coloanaPK]);
                        tnAdd.Name = dataReader[_coloanaPK].ToString();
                    }
                    else
                    {
                        if (_coloanaJurnal != null)
                            tnAdd.Tag = new NodeInfo(Convert.ToInt32(dataReader[_coloanaPK]), Convert.ToInt32(dataReader[_coloanaJurnal]));
                        else
                            tnAdd.Tag = new NodeInfo(Convert.ToInt32(dataReader[_coloanaPK]));
                    }
                    ///adauga randuri in grid
                    int index= ((DataGridViewRow)((NodeInfo)tr.Tag).GridRowNo).Index + rowNr;
                    dgv.Rows.Insert(index+1, 1);
                    if(dgv.Rows[index + 1].Cells["Art./Alin."]!=null)
                        dgv.Rows[index + 1].Cells["Art./Alin."].Value = tnAdd.Name.ToString().Trim();
                    ((NodeInfo)tnAdd.Tag).GridRowNo = dgv.Rows[index+1];
                    dgv.Rows[index + 1].Tag = tnAdd;
                    rowNr++;
                    areFii = true;
                }

            }
            if (areFii)
            { 
                //setaza parintele cu font bolduit
                TreeView tv = tr.TreeView;
                tr.NodeFont = new Font(tv.Font,FontStyle.Bold);
                ((DataGridViewRow)((NodeInfo)tr.Tag).GridRowNo).DefaultCellStyle.Font = tr.NodeFont;
                ((DataGridViewRow)((NodeInfo)tr.Tag).GridRowNo).ReadOnly = true;
                ((DataGridViewRow)((NodeInfo)tr.Tag).GridRowNo).DefaultCellStyle.BackColor = System.Drawing.SystemColors.InactiveBorder;
            }
            dataReader.Close();
            cmd.Dispose();
            if (areFii)
                tr.ImageIndex = 0;
            foreach (TreeNode tr1 in tr.Nodes)
                LoadTreeAndGrid(tr1, sqlConn, CodUnitate,dgv);
            tr.ExpandAll();
        }

        override public void Salvare(object sender, EventArgs args)
        {
            base.Salvare(sender, args);
            if (EroareSalvare)
                return;
            if (!newTreeDataControl)
            {
                ///incarca nodul modificat
                ///
                if (ReloadTree)
                {
                    SqlConnection sqlC = DeschideConexiune(workConnString);
                    Trace.Assert(_localTree != null, "Va rugam setati cotrolul de tip tree!");
                    TreeNode tnsel = _localTree.SelectedNode;
                    if (_localTree.SelectedNode != null)
                        LoadTree(_localTree.SelectedNode, sqlC, String.Empty);
                    else
                        LoadTree(_localTree.Nodes[0], sqlC, String.Empty);
                    _localTree.SelectedNode = tnsel;
                    InchideConexiune(sqlC);
                    ReloadTree = false;
                }
            }
        }

        private void treeView_AfterSelect(object sender, TreeViewEventArgs e)
        {
            TreeLoadHandler temp = HandleFillTree;
            if (temp != null)
                temp(sender, e);
            
            Text = numeMacheta + " - " + e.Node.Text;
        }

        private void treeView_BeforeSelect(object sender, TreeViewCancelEventArgs e)
        {
            if (listBndSourceMain.Count==0 || listBndSourceMain[0].DataSource == null)
                return;
            //daca sunt modificari in datele din gridul afisat
            DataSet _localDS = listBndSourceMain[0].DataSource as DataSet;
            if (_localDS.GetChanges() != null)
            {
                Salvare(this, null);
                SetStatus("Datele au fost salvate automat!!");
            }
            else
                SetStatus("");

        }

        private void FrmTreeRezumat_Load(object sender, EventArgs e)
        {
            SearchForTreeControl(this);
            if (_localTree != null)
            {
                _localTree.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.treeView_AfterSelect);
                if (!newTreeDataControl)
                {
                    _localTree.BeforeSelect += new System.Windows.Forms.TreeViewCancelEventHandler(this.treeView_BeforeSelect);
                }
                localTree.SelectedImageIndex = 2;
                localTree.ExpandAll();
            }
            
        }


        override public void Selectie(object sender, EventArgs args)
        {
            selectedRow = null;
            if (gridRezumat.Count == 0)
                throw (new NotSupportedException("Nu a fost setat gridul rezumat"));
            Int16 indDGV = GetCurrentGrid();
            Trace.Assert(indDGV != -1, "Nu s-au setat gridurile!!");
            if (!ReadOnly)
                Salvare(sender, args);
            if (this.gridRezumat[indDGV].CurrentRow == null || this.gridRezumat[indDGV].CurrentRow.IsNewRow)
            {
                if (localTree.SelectedNode == null)
                {
                    this.DialogResult = DialogResult.None;
                    MessageBox.Show("Va rugam selectati un rand existent in baza de date!", "Eroare", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                else
                {
                    TreeNode tns = localTree.SelectedNode;
                    BindingSource bs = gridRezumat[indDGV].DataSource as BindingSource;
                    if (bs != null)
                    {
                        bs.Filter = String.Empty;
                        NodeInfo ni = tns.Tag as NodeInfo;
                        int poz = bs.Find(_coloanaPK,ni.ID);
                        if (poz != -1)
                            bs.Position = poz;
                    }
                }
            }

            if (this.gridRezumat[indDGV] != null)
                selectedRow = this.gridRezumat[indDGV].CurrentRow;
            if (selectedRow != null)
                selectedDataRow = selectedRow.DataBoundItem as DataRowView;
            this.DialogResult = DialogResult.OK;
            /// daca nu e modal inchide macheta
            if (!this.Modal)
                this.Close();

        }

    }
    public delegate void TreeLoadHandler(object sender, TreeViewEventArgs args);
}
